package cn.hl.hm.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.hl.hm.dao.DriverMapper;
import cn.hl.hm.dao.TRechargeActivityMapper;
import cn.hl.hm.entity.Driver;
import cn.hl.hm.entity.RechargeRecoard;
import cn.hl.hm.entity.RoadFee;
import cn.hl.hm.entity.TRechargeActivity;
import cn.hl.hm.service.RechargeRecoardService;
import cn.hl.hm.service.RoadFeeService;
import cn.hl.hm.util.BeanPicUtil;
import cn.hl.hm.util.ExportData;
import cn.hl.hm.util.InfoCode;
import cn.hl.hm.util.Result;

 

/**
 * 导出excel
 * 
 * @author 星矢
 *
 */
@Controller
@RequestMapping("/exportController")
public class ExportController {
	
	private final static SimpleDateFormat shortSdf = new SimpleDateFormat("yyyy-MM-dd");
	private final static SimpleDateFormat hhmmSdf = new SimpleDateFormat("yyyyMMddHHmm");
	private static Logger logger = Logger.getLogger(ExportController.class);
	@Autowired
	DriverMapper driverMapper;
	@Autowired
	TRechargeActivityMapper tRechargeActivityMapper;
//	@Value("#{settings['exportBasePath']}")
//	String exportBasePath="/data/server/download/ex" ;
	@Autowired
	RechargeRecoardService rechargeRecoardService;
	
	@Autowired
    RoadFeeService roadFeeService;

	 

	@Autowired
	private BeanPicUtil beanPicUtil;
	/**
	 * 
	 * @param 状态：
	 * @param type
	 *           1:配载费管理（1、充值、2消费）
	 *           2：司机账户管理
	 *           
	 *           
	 *            
	 * @param value
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/exportDataByType", method = RequestMethod.GET)
	public void exportDataByType(Integer type, Integer value,RechargeRecoard rechargeRecoard, HttpServletRequest request,
			HttpServletResponse response) {
		logger.info("园区收费/配载费相关导出---司机账户明细导出/配载费收费列表导出---exportController/exportDataByType");
		try {
		String ctxPath = request.getSession().getServletContext().getRealPath("/") + "export/";
		String fileName = "";
		File file = new File(ctxPath.toString());

		if (!file.exists()) {
			file.mkdir();
			try {
				Thread.sleep(1500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		if (null == type || "null".equals(type) || null == type || "null".equals(type)) {
			Result.ok(null, InfoCode.FAILURE, response);
			return  ;
		}
		Map<String, Object> map = new HashMap<>();
		List<RoadFee> selectPageList=null;
		if (type == 1) {
		 
			RoadFee orderInfo = new RoadFee();
			 
		    selectPageList = roadFeeService.selectPageList(orderInfo);
			if (value == 1) { // 已关闭
				logger.info("导出配载费--收费列表");
				fileName=hhmmSdf.format(new Date())+".xls";
				ExportData.exportRoadFeeExcel(ctxPath + fileName, selectPageList);
			} 

		} else if (type == 2) { 
			try {
				 if(StringUtils.isNotBlank(rechargeRecoard.getBeString())&&StringUtils.isNotBlank(rechargeRecoard.getEndString())){
						if(rechargeRecoard.getBeString().trim().equals("''")){
//							Calendar cal=Calendar.getInstance();//使用日历类
//							rechargeRecoard.setBeString(cal.get(Calendar.YEAR)+"-01-01 00:00:00");
//							rechargeRecoard.setEndString(hhmmSdf.format(new Date()));
						}else if (rechargeRecoard.getEndString().trim().equals("''")) {
						}else if (rechargeRecoard.getBeString().trim().equals("\"\"")) {
						}else if (rechargeRecoard.getEndString().trim().equals("\"\"")) {
						}else {
							SimpleDateFormat shortSdf = new SimpleDateFormat("yyyy-MM-dd");
							   String str = rechargeRecoard.getEndString().trim();  
									try {
										Date dt = shortSdf.parse(str);
										Calendar rightNow = Calendar.getInstance();  
								        rightNow.setTime(dt);  
								        rightNow.add(Calendar.DAY_OF_YEAR, 1);// 日期加10天  
								        rechargeRecoard.setSearchEndTime(shortSdf.format(rightNow.getTime()) + " 23:59:59");
									} catch (ParseException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
							
							rechargeRecoard.setBeString(rechargeRecoard.getBeString().trim()+" 00:00:00");
							rechargeRecoard.setEndString(rechargeRecoard.getEndString().trim()+" 23:59:59");
						}
					}
//				 RechargeRecoard searchBeginAmount=new RechargeRecoard();
//				 searchBeginAmount.setSearchTime(rechargeRecoard.getBeString());
//				 RechargeRecoard searchEndAmount=new RechargeRecoard();
//				 searchEndAmount.setSearchEndTime(rechargeRecoard.getBeString());
				 
				 List<RechargeRecoard> rrList = rechargeRecoardService.driverCashDetail(rechargeRecoard);
//				 List<RechargeRecoard> rrListReturn = new ArrayList<>();
//				 for (RechargeRecoard rr : rrList) {
//					 searchBeginAmount.setDriverId(rr.getDriverId());
//					 searchEndAmount.setDriverId(rr.getDriverId());
//					 searchBeginAmount.setStatus("2");
//					 searchEndAmount.setStatus("2");
//					 List<RechargeRecoard> rrr = rechargeRecoardService.selectRechargeRecoardByUserPhone(searchBeginAmount);
//					 if(rrr!=null && rrr.size()>0){
//						 if(rrr.get(0).getRemainCash()!=null){
//							 if(rrr.get(0).getOperType()==2){
//								 rr.setBeginAmount(rrr.get(0).getRemainCash().toString());
//							 }else{
//								 rr.setBeginAmount(rrr.get(0).getRemainCash().subtract(rrr.get(0).getAmount()).toString());
//							 }
//							
//						 }else{
//							 rr.setBeginAmount("0");
//						 }
//					 }else{
//						 //如果选择的日期 没有发生交易记录。则获取小于该日期的记录，按照日期倒叙，并取第一条
//						 List<RechargeRecoard> rrr2 = rechargeRecoardService.selectRechargeRecoardByUserPhone(searchEndAmount);
//						 if(rrr2!=null && rrr2.size()>0){
//							 if(rrr2.get(0).getRemainCash()!=null){
//								 if(rrr2.get(0).getOperType()==1){
//									 rr.setBeginAmount(rrr2.get(0).getRemainCash().subtract(rrr2.get(0).getAmount()).toString());
//								 }else{
//									 rr.setBeginAmount(rrr2.get(0).getRemainCash().toString());
//								 }
//								
//							 }else{
//								 rr.setBeginAmount("0");
//							 }
//						 }
//					 }
//					 RechargeRecoard searchEndAmount1=new RechargeRecoard();
//					 searchEndAmount1.setSearchEndTime(rechargeRecoard.getEndString());
//					 searchEndAmount1.setDriverId(rr.getDriverId());
//					 searchEndAmount1.setStatus("2");
//					 RechargeRecoard searchBeginAmount1=new RechargeRecoard();
//					 searchBeginAmount1.setSearchTime(rechargeRecoard.getEndString());
//					 searchBeginAmount1.setStatus("2");
//					 searchBeginAmount1.setDriverId(rr.getDriverId());
//					 List<RechargeRecoard> rrr2 = rechargeRecoardService.selectRechargeRecoardByUserPhone(searchBeginAmount1);
//					 if(rrr2!=null && rrr2.size()>0){
//						 if(rrr2.get(0).getRemainCash()!=null){
//							 rr.setEndAmount(rrr2.get(0).getRemainCash().toString());
//						 }else{
//							 rr.setEndAmount("0");
//						 }
//					 }else{
////		                 // 如果大于该日期的 不存在，就取小于该日期的第一条
////						 List<RechargeRecoard> rrrr = rechargeRecoardService.selectRechargeRecoardByUserPhone(searchEndAmount1);
////						 if(rrrr!=null && rrrr.size()>0){
////							 if(rrrr.get(0).getRemainCash()!=null){
////								 rr.setEndAmount(rrrr.get(0).getRemainCash().toString());
////							 }else{
//								 rr.setEndAmount("0");
////							 }
////						 }
//						 }
//					 rrListReturn.add(rr);
//				}
				  fileName=hhmmSdf.format(new Date())+".xls";
					ExportData.exportDriverAccountExcel(ctxPath + fileName, rrList);
				
				
				
			} catch (Exception e) {
				e.printStackTrace();
				logger.error(e);
				Result.ok(null, InfoCode.FAILURE, response);
			}

		}  else if (type == 3) 
		{
			// 充值记录导出
			try{
				if(StringUtils.isNotBlank(rechargeRecoard.getBeString())&&StringUtils.isNotBlank(rechargeRecoard.getEndString())){
					if(rechargeRecoard.getBeString().trim().equals("''")){
						
					}else if (rechargeRecoard.getEndString().trim().equals("''")) {
						
					}else if (rechargeRecoard.getBeString().trim().equals("\"\"")) {
						
					}else if (rechargeRecoard.getEndString().trim().equals("\"\"")) {
						
					}else {
						rechargeRecoard.setBeString(rechargeRecoard.getBeString().trim()+" 00:00:00");
						rechargeRecoard.setEndString(rechargeRecoard.getEndString().trim()+" 23:59:59");
					}
				}
				rechargeRecoard.setType(null);
				rechargeRecoard.setOperType(1);
				rechargeRecoard.setStatus("2");
				List<RechargeRecoard> rechargeRecoardList = rechargeRecoardService.selectRechargeRecoardAss(rechargeRecoard);
				fileName=hhmmSdf.format(new Date())+".xls";
				ExportData.exportRechargeExcel(ctxPath + fileName, rechargeRecoardList);
			}catch(Exception e){
				e.printStackTrace();
			}
		}else{
			
		}
//			response.reset();
////			response.setHeader("content-type","application/x-gzip");
//			HttpHeaders headers = new HttpHeaders();
//			File file1 = new File(ctxPath + fileName);
//			fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");// 为了解决中文名称
//			headers.setContentDispositionFormData("attachment", fileName);
//			headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//			logger.info("导出配载费--收费列表END"+ctxPath + fileName);
//			return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file1), headers, HttpStatus.CREATED);
		
	    FileInputStream input=new FileInputStream(ctxPath + fileName);
		 OutputStream output=response.getOutputStream();
		 response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));
		 byte[] b=new byte[1024];
		 int len=0;
		 while((len=input.read(b))!=-1){
			 output.write(b,0,len);
		 }
		 input.close();
		 output.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return  ;
	}
	/**
	 * 
	 * @param 状态：
	 * @param type
	 *           1:配载费管理（1、充值、2消费）
	 * @param value
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/exportRechargeRecoard", method = RequestMethod.GET)
	public void exportRechargeRecoard(  HttpServletRequest request,String userphone,
			HttpServletResponse response) {
		logger.info("配载费相关导出---充值列表导出---exportController/exportRechargeRecoard");
		try {
		String ctxPath = request.getSession().getServletContext().getRealPath("/") + "export/";
		String fileName = "";
		File file = new File(ctxPath.toString());

		if (!file.exists()) {
			file.mkdir();
			try {
				Thread.sleep(1500);
			} catch (InterruptedException e) {
				e.printStackTrace(); 
			}
		}
		RechargeRecoard rechargeRecoard = new RechargeRecoard();
		if(request.getParameter("userphone")!=null){
			rechargeRecoard.setUserphone(request.getParameter("userphone"));
		}
		 
//		rechargeRecoard.setOperType(1);
		rechargeRecoard.setStatus("2");
		List<RechargeRecoard> rechargeRecoardList = rechargeRecoardService.selectRechargeRecoard(rechargeRecoard);
		fileName=hhmmSdf.format(new Date())+".xls";
	    ExportData.exportRechargeRecoardExcel(ctxPath + fileName, rechargeRecoardList);
			 
	     FileInputStream input=new FileInputStream(ctxPath + fileName);
		 OutputStream output=response.getOutputStream();
		 response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));
		 byte[] b=new byte[1024*1024];
		 int len=0;
		 while((len=input.read(b))!=-1){
			 output.write(b,0,len);
		 }
		 input.close();
		 output.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return  ;
	}
	
	
	
	
	@RequestMapping(value = "/selectSecurityListExport", method = RequestMethod.POST)
	public void selectSecurityListExport(  HttpServletRequest request, RechargeRecoard rechargeRecoard,
			HttpServletResponse response) {
		logger.info("配载费相关导出---充值列表导出---exportController/exportRechargeRecoard");
		try {
		String ctxPath = request.getSession().getServletContext().getRealPath("/") + "export/";
		String fileName = "";
		File file = new File(ctxPath.toString());

		if (!file.exists()) {
			file.mkdir();
			try {
				Thread.sleep(1500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		if (StringUtils.isNotBlank(rechargeRecoard.getBeString())
				&& StringUtils.isNotBlank(rechargeRecoard.getEndString())) {
			if (rechargeRecoard.getBeString().trim().equals("''")) {

			} else if (rechargeRecoard.getEndString().trim().equals("''")) {

			} else if (rechargeRecoard.getBeString().trim().equals("\"\"")) {

			} else if (rechargeRecoard.getEndString().trim().equals("\"\"")) {

			} else {
				rechargeRecoard.setBeString(rechargeRecoard.getBeString().trim() + " 00:00:00");
				rechargeRecoard.setEndString(rechargeRecoard.getEndString().trim() + " 23:59:59");
			}
		}

		 
		List<RechargeRecoard> rechargeRecoardList = rechargeRecoardService.selectSecurityList(rechargeRecoard);
		fileName=hhmmSdf.format(new Date())+".xls";
	    ExportData.exportSecurityListExcel(ctxPath + fileName, rechargeRecoardList);
			 
	     FileInputStream input=new FileInputStream(ctxPath + fileName);
		 OutputStream output=response.getOutputStream();
		 response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));
		 byte[] b=new byte[1024*1024];
		 int len=0;
		 while((len=input.read(b))!=-1){
			 output.write(b,0,len);
		 }
		 input.close();
		 output.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return  ;
	}
	

}
